<template>
  <div class="asset-info-form">
    <el-form v-loading="loading">
      <el-form-item prop="pictures">
        <el-upload
          v-if="fileInput"
          class="upload-demo"
          drag
          :action="QINIUUPLOADURL"
          :data="qiniuData"
          :on-success="handleAvatarSuccess"
          :on-remove="handleRemovePic"
          :on-error="handleError"
          :before-upload="beforeAvatarUpload"
          :on-preview="$imgPreview"
          :file-list="qiniuData.fileList"
          :limit="1"
          :on-exceed="handleExceed"
          :multiple="false"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
            <div class="el-upload__text">文件大小不能超过300MB</div>
          </div>
        </el-upload>
        <el-form-item label="资源路径：" v-if="filePathInput">
          <el-input :disabled="true" v-model="filePath" clearable></el-input>
        </el-form-item>
      </el-form-item>
    </el-form>
  </div>
</template>
<style>
.el-input.is-disabled .el-input__inner {
  cursor: text;
}
</style>
<script>
import { qnToken } from '@/api/api'
import util from '@/utils/util'

export default {
  props: {},
  data() {
    return {
      fileInput: true,
      filePathInput: false,
      loading: false,
      filePath: '',
      qiniuData: {
        //上传图片携带的参数
        token: '',
        key: '',
        fileList: [],
      },
    }
  },
  created() {
    let that = this
    that.getToken()
  },
  methods: {
    getToken() {
      //上传之前获取 token
      qnToken({}).then((result) => {
        this.qiniuData.token = result.data
      })
    },
    beforeAvatarUpload: function (file) {
      //重命名和校验
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      this.qiniuData.key = 'ilink_' + new Date().getTime() + fielType
      //this.qiniuData.key = file.name;
      const isLt300M = file.size / 1024 / 1024 < 300
      if (!isLt300M) {
        this.$message.error('文件大小不能超过 300MB!')
        return false
      }
      this.loading = true
    },
    handleAvatarSuccess: function (res, file, fileList) {
      //上传成功
      this.qiniuData.fileList = fileList
      this.filePath = QINIUUPLOADURL.indexOf('uploadFile')>-1? res.data:QINIUPATH+res.key
      this.loading = false
      this.fileInput = false
      this.filePathInput = true
      this.$message({
        message: '上传成功',
        type: 'success',
      })
    },
    handleRemovePic: function (file, fileList) {
      //删除成功
      this.qiniuData.fileList = fileList
    },
    handleError: function (res) {
      this.$message({
        message: '上传失败',
        duration: 2000,
        type: 'warning',
      })
      this.loading = false
      this.fileInput = true
      this.filePathInput = false
    },
    handleExceed(files, fileList) {
      //文件超出个数限制时的钩子
      this.$message.warning(`只能上传一张图片！`)
    },
  },
}
</script>
